<template>
  <div class="record-dashboard">
    <header class="mb-8">
      <h1 class="glow-text">记录管理</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <!-- 记录状态卡片 -->
    <div class="card mb-8">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-medium">记录状态</h2>
        <div class="flex space-x-2">
          <button 
            v-if="!recordStatus.is_running" 
            @click="showStartRecordModal = true" 
            class="btn btn-primary"
          >
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            开始记录
          </button>
          <button 
            v-else 
            @click="stopRecording" 
            class="btn btn-danger"
          >
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z"></path>
            </svg>
            停止记录
          </button>
          <button @click="refreshStatus" class="btn btn-outline">
            <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
            刷新
          </button>
        </div>
      </div>

      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>

      <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="bg-dark-darker p-6 rounded-lg">
          <div class="flex items-center mb-4">
            <div class="w-3 h-3 rounded-full mr-2" :class="recordStatus.is_running ? 'bg-accent-blue animate-pulse' : 'bg-accent-pink'"></div>
            <h3 class="text-lg font-medium">记录状态</h3>
          </div>
          <div class="text-2xl font-bold mb-2">{{ recordStatus.is_running ? '正在记录' : '未记录' }}</div>
          <div class="text-light-dark">
            <div v-if="recordStatus.is_running">
              <div>网络接口: {{ recordStatus.interface || 'N/A' }}</div>
              <div>监控服务数: {{ recordStatus.services?.length || 0 }}</div>
              <div>开始时间: {{ formatTime(recordStatus.start_time) }}</div>
            </div>
            <div v-else>
              上次记录时间: {{ recordStatus.last_record_time ? formatTime(recordStatus.last_record_time) : '无记录' }}
            </div>
          </div>
        </div>

        <div class="bg-dark-darker p-6 rounded-lg">
          <h3 class="text-lg font-medium mb-4">记录统计</h3>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <div class="text-light-dark mb-1">记录服务数</div>
              <div class="text-2xl font-bold">{{ stats.serviceCount }}</div>
            </div>
            <div>
              <div class="text-light-dark mb-1">请求记录数</div>
              <div class="text-2xl font-bold">{{ stats.requestCount }}</div>
            </div>
            <div>
              <div class="text-light-dark mb-1">今日新增</div>
              <div class="text-2xl font-bold">{{ stats.todayCount }}</div>
            </div>
            <div>
              <div class="text-light-dark mb-1">平均响应时间</div>
              <div class="text-2xl font-bold">{{ stats.avgResponseTime }}ms</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速导航 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      <router-link to="/record/services" class="tech-card hover:border-primary transition-all duration-300">
        <div class="flex items-center mb-4">
          <svg class="w-6 h-6 mr-3 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
          </svg>
          <h3 class="text-xl font-medium">记录服务</h3>
        </div>
        <p class="text-light-dark mb-4">管理需要记录的服务，包括添加、编辑和删除记录服务。</p>
        <div class="text-primary">查看记录服务 →</div>
      </router-link>

      <router-link to="/record/requests" class="tech-card hover:border-primary transition-all duration-300">
        <div class="flex items-center mb-4">
          <svg class="w-6 h-6 mr-3 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path>
          </svg>
          <h3 class="text-xl font-medium">请求记录</h3>
        </div>
        <p class="text-light-dark mb-4">查看已记录的请求，包括请求详情、响应内容和转换为请求定义。</p>
        <div class="text-primary">查看请求记录 →</div>
      </router-link>
    </div>

    <!-- 最近记录的请求 -->
    <div class="card">
      <div class="flex justify-between items-center mb-6">
        <h2 class="text-xl font-medium">最近记录的请求</h2>
        <router-link to="/record/requests" class="btn btn-outline text-sm">查看全部</router-link>
      </div>

      <div v-if="loadingRequests" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
      </div>

      <div v-else-if="recentRequests.length === 0" class="text-center py-12 text-light-dark">
        暂无请求记录
      </div>

      <div v-else class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-dark-light">
              <th class="py-3 px-4 text-left">服务</th>
              <th class="py-3 px-4 text-left">路径</th>
              <th class="py-3 px-4 text-left">方法</th>
              <th class="py-3 px-4 text-left">状态码</th>
              <th class="py-3 px-4 text-left">响应时间</th>
              <th class="py-3 px-4 text-left">记录时间</th>
              <th class="py-3 px-4 text-left">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="request in recentRequests"
              :key="request._id"
              class="border-b border-dark-light hover:bg-dark-darker"
            >
              <td class="py-3 px-4">{{ request.service_name }}</td>
              <td class="py-3 px-4 font-mono text-sm truncate max-w-xs">{{ request.path }}</td>
              <td class="py-3 px-4">
                <span :class="{
                  'badge badge-blue': request.method === 'GET',
                  'badge badge-green': request.method === 'POST',
                  'badge badge-purple': request.method === 'PUT',
                  'badge badge-orange': request.method === 'DELETE',
                  'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)
                }">{{ request.method }}</span>
              </td>
              <td class="py-3 px-4">
                <span :class="{
                  'text-accent-blue': request.status_code < 300,
                  'text-accent-yellow': request.status_code >= 300 && request.status_code < 400,
                  'text-accent-orange': request.status_code >= 400 && request.status_code < 500,
                  'text-accent-pink': request.status_code >= 500
                }">{{ request.status_code }}</span>
              </td>
              <td class="py-3 px-4">{{ request.response_time.toFixed(2) }} ms</td>
              <td class="py-3 px-4 text-light-dark">{{ formatTime(request.created_at) }}</td>
              <td class="py-3 px-4">
                <router-link :to="`/record/requests/${request._id}`" class="text-primary hover:text-primary-light mr-2" title="查看详情">
                  <svg class="w-5 h-5 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                  </svg>
                </router-link>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 开始记录弹窗 -->
    <div v-if="showStartRecordModal" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-lg cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">开始记录</h2>
            <button @click="showStartRecordModal = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-6">
            <label class="block text-light-dark mb-2">网络接口</label>
            <input
              v-model="recordForm.interface"
              type="text"
              class="input w-full"
              placeholder="例如: eth0"
            />
          </div>

          <div class="mb-6">
            <label class="block text-light-dark mb-2">选择服务</label>
            <div v-if="loadingServices" class="flex justify-center items-center py-4">
              <div class="animate-spin rounded-full h-6 w-6 border-t-2 border-b-2 border-primary"></div>
            </div>
            <div v-else-if="recordServices.length === 0" class="text-center py-4 text-light-dark">
              暂无记录服务，请先添加记录服务
            </div>
            <div v-else class="max-h-60 overflow-y-auto bg-dark-darker rounded-lg p-2">
              <div
                v-for="service in recordServices"
                :key="service._id"
                class="flex items-center p-2 hover:bg-dark-light rounded-md"
              >
                <input
                  type="checkbox"
                  :id="`service-${service._id}`"
                  v-model="recordForm.service_ids"
                  :value="service._id"
                  class="mr-2"
                />
                <label :for="`service-${service._id}`" class="flex-1 cursor-pointer">
                  <div>{{ service.service_name }}</div>
                  <div class="text-sm text-light-dark">{{ service.service_ip }}:{{ service.service_port }}</div>
                </label>
              </div>
            </div>
          </div>

          <div class="flex justify-end">
            <button @click="showStartRecordModal = false" class="btn btn-outline mr-2">取消</button>
            <button @click="startRecording" class="btn btn-primary" :disabled="startingRecord">
              <span v-if="startingRecord">开始中...</span>
              <span v-else>开始记录</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { recordApi } from '../../api';

// 状态变量
const loading = ref(false);
const loadingRequests = ref(false);
const loadingServices = ref(false);
const startingRecord = ref(false);
const showStartRecordModal = ref(false);

// 记录状态
const recordStatus = ref({
  is_running: false,
  interface: '',
  services: [] as any[],
  start_time: '',
  last_record_time: ''
});

// 统计数据
const stats = ref({
  serviceCount: 0,
  requestCount: 0,
  todayCount: 0,
  avgResponseTime: 0
});

// 最近请求记录
const recentRequests = ref<any[]>([]);

// 记录服务列表
const recordServices = ref<any[]>([]);

// 记录表单
const recordForm = ref({
  interface: 'eth0',
  service_ids: [] as string[]
});

// 获取记录状态
const fetchRecordStatus = async () => {
  try {
    loading.value = true;
    const response = await recordApi.getRecordStatus();
    
    if (response && typeof response === 'object') {
      recordStatus.value = {
        is_running: response.is_running || false,
        interface: response.interface || '',
        services: Array.isArray(response.services) ? response.services : [],
        start_time: response.start_time || '',
        last_record_time: response.last_record_time || ''
      };
    }
  } catch (error) {
    console.error('获取记录状态失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取统计数据
const fetchStats = async () => {
  try {
    // 这里应该有一个获取统计数据的API，暂时使用模拟数据
    stats.value = {
      serviceCount: 5,
      requestCount: 128,
      todayCount: 24,
      avgResponseTime: 45.8
    };
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取最近请求记录
const fetchRecentRequests = async () => {
  try {
    loadingRequests.value = true;
    const response = await recordApi.getRequests({ page: 1, page_size: 5 });
    
    if (response && typeof response === 'object' && Array.isArray(response.requests)) {
      recentRequests.value = response.requests.map((req: any) => ({
        ...req,
        response_time: req.response_time || 0
      }));
    } else {
      // 模拟数据
      recentRequests.value = [
        {
          _id: '1',
          service_name: 'user-service',
          path: '/api/users/123',
          method: 'GET',
          status_code: 200,
          response_time: 45.2,
          created_at: new Date(Date.now() - 120000).toISOString()
        },
        {
          _id: '2',
          service_name: 'order-service',
          path: '/api/orders',
          method: 'POST',
          status_code: 201,
          response_time: 78.5,
          created_at: new Date(Date.now() - 180000).toISOString()
        },
        {
          _id: '3',
          service_name: 'payment-service',
          path: '/api/payments/456',
          method: 'PUT',
          status_code: 204,
          response_time: 32.1,
          created_at: new Date(Date.now() - 240000).toISOString()
        }
      ];
    }
  } catch (error) {
    console.error('获取最近请求记录失败:', error);
  } finally {
    loadingRequests.value = false;
  }
};

// 获取记录服务列表
const fetchRecordServices = async () => {
  try {
    loadingServices.value = true;
    const response = await recordApi.getServices();
    
    if (response && typeof response === 'object' && Array.isArray(response.services)) {
      recordServices.value = response.services;
    } else {
      // 模拟数据
      recordServices.value = [
        {
          _id: '1',
          service_name: 'user-service',
          service_ip: '10.0.0.1',
          service_port: 8080,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          _id: '2',
          service_name: 'order-service',
          service_ip: '10.0.0.2',
          service_port: 8081,
          is_active: true,
          created_at: new Date().toISOString()
        },
        {
          _id: '3',
          service_name: 'payment-service',
          service_ip: '10.0.0.3',
          service_port: 8082,
          is_active: true,
          created_at: new Date().toISOString()
        }
      ];
    }
  } catch (error) {
    console.error('获取记录服务列表失败:', error);
  } finally {
    loadingServices.value = false;
  }
};

// 开始记录
const startRecording = async () => {
  if (!recordForm.interface || recordForm.service_ids.length === 0) {
    alert('请选择网络接口和至少一个服务');
    return;
  }

  try {
    startingRecord.value = true;
    await recordApi.startRecording({
      interface: recordForm.interface,
      service_ids: recordForm.service_ids
    });
    
    showStartRecordModal.value = false;
    recordForm.service_ids = [];
    
    // 刷新状态
    await fetchRecordStatus();
  } catch (error: any) {
    console.error('开始记录失败:', error);
    alert(`开始记录失败: ${error.response?.data?.error || error.message}`);
  } finally {
    startingRecord.value = false;
  }
};

// 停止记录
const stopRecording = async () => {
  if (!confirm('确定要停止记录吗？')) return;

  try {
    loading.value = true;
    await recordApi.stopRecording();
    
    // 刷新状态
    await fetchRecordStatus();
  } catch (error: any) {
    console.error('停止记录失败:', error);
    alert(`停止记录失败: ${error.response?.data?.error || error.message}`);
  } finally {
    loading.value = false;
  }
};

// 刷新状态
const refreshStatus = async () => {
  await fetchRecordStatus();
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '未知';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN');
};

// 定时刷新
let refreshInterval: number | null = null;

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    fetchRecordStatus(),
    fetchStats(),
    fetchRecentRequests(),
    fetchRecordServices()
  ]);

  // 设置定时刷新
  refreshInterval = window.setInterval(() => {
    if (recordStatus.value.is_running) {
      fetchRecordStatus();
      fetchRecentRequests();
    }
  }, 10000);
});

onUnmounted(() => {
  if (refreshInterval !== null) {
    clearInterval(refreshInterval);
  }
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
